<template>
  <div class="inp">
    <h2>任务列表</h2>
    <!-- 输入框和添加按钮 -->
    <input v-model="newTask" type="text" placeholder="添加新任务" />
    <button @click="addTask">添加</button>

    <!-- 当没有未完成任务时显示 -->
    <p v-if="!hasIncompleteTasks && !hasCompletedTasks">没有任务</p>

    <!-- 当有未完成任务时显示 -->
    <ul v-else>
      <li v-for="(task, index) in tasks" :key="index" :class="{ 'completed': task.completed, 'not-completed': !task.completed }">
        <span>{{ task.name }}</span>
        <span v-if="task.completed">(已完成)</span>
        <span v-else>(未完成)</span>
        <button @click="toggleTaskStatus(index)">切换状态</button>
      </li>
    </ul>

    <!-- 显示已完成任务的数量 -->
    <p>已完成任务数：{{ completedTasksCount }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

// 任务数据模型
interface Task {
  name: string;
  completed: boolean;
}

// 任务列表
const tasks = ref<Task[]>([]);

// 新任务输入
const newTask = ref('');

// 添加新任务
const addTask = () => {
  if (newTask.value.trim() !== '') {
    tasks.value.push({
      name: newTask.value,
      completed: false
    });
    newTask.value = ''; // 清空输入框
  }
};

// 切换任务完成状态
const toggleTaskStatus = (index: number) => {
  tasks.value[index].completed = !tasks.value[index].completed;
};


// 计算已完成任务的数量
const completedTasksCount = computed(() => tasks.value.filter(task => task.completed).length);

// 检查是否有未完成的任务
const hasIncompleteTasks = computed(() => tasks.value.some(task => !task.completed));

// 检查是否有已完成的任务
const hasCompletedTasks = computed(() => tasks.value.some(task => task.completed));
</script>

<style scoped>
ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 10px 0;
  padding: 5px;
  display: flex;
  justify-content: space-between;
  border: 1px solid #ccc;
  border-radius: 4px;
  position: relative; /* 用于绝对定位图标 */
}

.completed::before {
  content: '✓';
  color: green;
  position: absolute;
  left: -10px;
}

.not-completed::before {
  content: '✗';
  color: red;
  position: absolute;
  left: -10px;
}

.completed span {
  color: green;
  text-decoration: line-through;
}

.not-completed span {
  color: black;
}

.inp button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
  margin-left: 10px;
}

.inp button:hover {
  background-color: #0056b3;
}

input {
  padding: 5px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>